"""
认证相关API路由
"""
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.database import get_db
from app.schemas.user import UserLogin, Token, UserRegister
from app.schemas.common import DataResponse, MessageResponse
from app.services.user_service import user_service

router = APIRouter()


@router.post("/login", response_model=DataResponse[Token])
async def login(
    *,
    db: AsyncSession = Depends(get_db),
    login_data: UserLogin
) -> DataResponse[Token]:
    """
    用户登录
    """
    result = await user_service.login(db, login_data=login_data)
    token_data = Token(
        access_token=result["access_token"],
        refresh_token=result["refresh_token"],
        token_type=result["token_type"],
        expires_in=result["expires_in"]
    )
    
    return DataResponse(
        data=token_data,
        message="登录成功"
    )


@router.post("/register", response_model=DataResponse[Token], status_code=status.HTTP_201_CREATED)
async def register(
    *,
    db: AsyncSession = Depends(get_db),
    register_data: UserRegister
) -> DataResponse[Token]:
    """
    用户注册并自动登录
    """
    # 验证密码匹配
    if not register_data.passwords_match():
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="密码和确认密码不匹配"
        )
    
    # 创建用户
    from app.schemas.user import UserCreate
    user_create = UserCreate(
        username=register_data.username,
        email=register_data.email,
        password=register_data.password,
        full_name=register_data.full_name,
        organization=register_data.organization,
        phone=register_data.phone,
        bio=register_data.bio
    )
    
    user = await user_service.create_user(db, user_create=user_create)
    
    # 自动登录
    login_data = UserLogin(
        username=register_data.username,
        password=register_data.password
    )
    
    result = await user_service.login(db, login_data=login_data)
    token_data = Token(
        access_token=result["access_token"],
        refresh_token=result["refresh_token"],
        token_type=result["token_type"],
        expires_in=result["expires_in"]
    )
    
    return DataResponse(
        data=token_data,
        message="注册成功并已自动登录"
    )


@router.post("/refresh", response_model=DataResponse[Token])
async def refresh_access_token(
    *,
    db: AsyncSession = Depends(get_db),
    refresh_token: str
) -> DataResponse[Token]:
    """
    刷新访问令牌
    """
    result = await user_service.refresh_token(db, refresh_token=refresh_token)
    token_data = Token(
        access_token=result["access_token"],
        refresh_token=result["refresh_token"],
        token_type=result["token_type"],
        expires_in=result["expires_in"]
    )
    
    return DataResponse(
        data=token_data,
        message="令牌刷新成功"
    )


@router.post("/logout", response_model=MessageResponse)
async def logout() -> MessageResponse:
    """
    用户登出
    注意：由于使用JWT，登出主要在客户端处理(删除本地令牌)
    这里可以实现令牌黑名单等机制
    """
    # 这里可以实现登出逻辑，比如：
    # 1. 将令牌加入黑名单
    # 2. 记录登出日志
    # 3. 清除相关缓存等
    
    return MessageResponse(message="登出成功")


@router.post("/verify-token", response_model=MessageResponse)
async def verify_token(
    *,
    db: AsyncSession = Depends(get_db),
    token: str
) -> MessageResponse:
    """
    验证令牌有效性
    """
    from app.core.security import verify_token as verify_jwt_token
    
    user_id = verify_jwt_token(token)
    if not user_id:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="无效的令牌"
        )
    
    # 检查用户是否存在且活跃
    user = await user_service.get_user_by_id(db, user_id=int(user_id))
    if not user or not user.is_active:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户不存在或已禁用"
        )
    
    return MessageResponse(message="令牌有效")